package file.download;


import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;

//文件下载
public class download extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      /* resp.setContentType("text/html;charset=utf-8");
         String user_agent =  req.getHeader("user-agent");
        System.out.println("启动");
  resp.getWriter().write(user_agent);
  if(user_agent.contains("Firefox")){
      resp.getWriter().write("<hr/>"+"我是火狐");
  }else {
      resp.getWriter().write("<hr/>"+"我不是火狐");
  }*/
        String name = "小狗.jpg";
        String user_agent = req.getHeader("user-agent");
        //获取文件扩展类型
        String str = getServletContext().getMimeType("E:\\Test\\小狗.jpg");
        //设置文件扩展类型
        resp.setHeader("Content/type",str);
//        resp.setContentType(str); //设置文件扩展类型
        //告诉客户端收到的数据用于下载使用
        //Content-Disposition告诉响应头收到的数据怎样处理
        //attachment 表示附件   表示下载使用
        //filename表示指定下载的文件名称
        //URLEncoder.encode("小狗.jpg","UTF-8") 表示把中文名进行UTF-8编码操作
        System.out.println("启动");
        if(user_agent.contains("Firefox")) {
            Base64.Encoder encoder = Base64.getEncoder();
            String decode = new String(encoder.encode(name.getBytes()));
            System.out.println(decode);
            resp.setHeader("Content-Disposition", "attachment;fileName="+decode);
            }else {
//            resp.setContentType("text/heml;charset=utf-8");
            resp.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("小狗.jpg", "UTF-8"));
        }
        //创建文件输出流
        FileInputStream in = new FileInputStream("E:\\Test\\小狗.jpg");
        //获取文件输入流输入到浏览器中
        ServletOutputStream servletout = resp.getOutputStream();
        IOUtils.copy(in,servletout);
        in.close();

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
